//
//  MyselfViewController.m
//  HDYS
//
//  Created by qianfeng on 15-4-22.
//  Copyright (c) 2015年 kay. All rights reserved.
//

#import "MyselfViewController.h"
#import "MyselfFirstCell.h"
#import "MyselfCell.h"
#import "NearbyTradeVC.h"

#import "ForgetVC.h"
#import "Header.h"
#import "PersonInfoViewController.h"



@interface MyselfViewController () <UITextFieldDelegate, UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) UIScrollView *sv;

//导航栏标题视图底部视图
@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) NSArray *registerTFArray;

@property (nonatomic, assign) BOOL isRegisterSuccess;

@end

@implementation MyselfViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    //登陆之后的界面
    [self createPersonCenter];
    //登陆时界面
    [self createScrollView];
    [self createLandInNav];
}

-(void)viewWillAppear:(BOOL)animated{
    if (isLandIn) {
        //已经登陆的时候,隐藏登陆界面
        self.sv.hidden = YES;
    } else{
        //未登陆时,显示
        self.sv.hidden = NO;
    }
}

#pragma mark - 登陆之后的界面
-(void)createPersonCenter{
    UITableView *infoTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    infoTableView.tag = 500;
    infoTableView.sectionHeaderHeight = 0;
    infoTableView.delegate = self;
    infoTableView.dataSource = self;
    [self.view addSubview:infoTableView];
}


#pragma mark - 未登陆地界面
//创建导航栏元素
-(void)createLandInNav{
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 25)];
    NSArray *array = @[@"登陆",@"注册"];
    for (int i = 0; i < array.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = 500 + i;
        btn.frame = CGRectMake(i * (backView.frame.size.width * 2 / 3), 0, backView.frame.size.width / 3, backView.frame.size.height - 5);
        [btn setTitle:array[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        [btn addTarget:self action:@selector(naviBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [backView addSubview:btn];
    }
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, backView.frame.size.height - 5, backView.frame.size.width / 3, 5)];
    bottomView.backgroundColor = [UIColor redColor];
    [backView addSubview:bottomView];
    self.bottomView = bottomView;
    self.navigationItem.titleView = backView;
}

//创建登陆页面
-(void)createScrollView{
    UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49)];
    sv.contentSize = CGSizeMake(SCREEN_WIDTH * 2, SCREEN_HEIGHT - 64 - 49);
    //
    sv.tag = 33;
    sv.pagingEnabled = YES;
    sv.bounces = NO;
    sv.alwaysBounceHorizontal = NO;
    sv.backgroundColor = [UIColor whiteColor];
    sv.delegate = self;
    [self.view addSubview:sv];
    self.sv = sv;
    
    float y[2] = {9.5 , 91};
    for (int i = 0; i < 2; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, y[i], SCREEN_WIDTH, 0.5)];
        view.backgroundColor = [UIColor grayColor];
        [sv addSubview:view];
    }
    
    NSArray *placeHoderTitle = @[@"用户名",@"密码"];
    CGFloat textFielH = 40;
    for (int i = 0; i < placeHoderTitle.count; i++) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 10 + i * textFielH, SCREEN_WIDTH-30, textFielH)];
        textField.tag = 400 + i;
        textField.placeholder = placeHoderTitle[i];
        textField.borderStyle = UITextBorderStyleNone;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.delegate = self;
        if ( i == 1) {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, 50, SCREEN_WIDTH - 10, 0.5)];
            lineView.backgroundColor = [UIColor grayColor];
            [sv addSubview:lineView];
            textField.secureTextEntry = YES;
        }
        [self.sv addSubview:textField];
    }
    UITextField *view = (UITextField *)[sv viewWithTag:401];
    UIButton *landBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    landBtn.frame = CGRectMake(10, view.frame.origin.y + view.frame.size.height + 10, SCREEN_WIDTH - 20, textFielH);
    [landBtn setTitle:@"登陆" forState:UIControlStateNormal];
    UIImage *image = [UIImage imageNamed:@"cancle_button"];
    UIImage *newImage = [image stretchableImageWithLeftCapWidth:5 topCapHeight:20];
    [landBtn setBackgroundImage:newImage forState:UIControlStateNormal];
    landBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [landBtn addTarget:self action:@selector(landBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [sv addSubview:landBtn];
    
    UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat forgetBtnW = 100;
    forgetBtn.frame = CGRectMake(SCREEN_WIDTH - 10 - forgetBtnW, landBtn.frame.origin.y + landBtn.frame.size.height + 10, forgetBtnW, 20);
    [forgetBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    forgetBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [forgetBtn addTarget:self action:@selector(forgetBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [sv addSubview:forgetBtn];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, SCREEN_WIDTH, 30)];
    label.text = @"使用其他账号登陆";
    label.backgroundColor = [UIColor lightGrayColor];
    label.textAlignment = NSTextAlignmentCenter;
    [sv addSubview:label];
    
    NSArray *array = @[@"ipadShareSina@2x",@"ipadShareWX@2x"];
    CGFloat btnW = 50.0f;
    CGFloat btnSpace = 20.0f;
    for (int i = 0; i < array.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake((SCREEN_WIDTH - 2 * btnW - btnSpace) / 2 + i * (btnW + btnSpace), label.frame.origin.y + label.frame.size.height + btnSpace, btnW, btnW);
        [btn setImage:[UIImage imageNamed:array[i]] forState:UIControlStateNormal];
        [sv addSubview:btn];
    }
    [self createRegister];
}

//创建注册页面
-(void)createRegister{
    float y[2] = {9.5, 131};
    for (int i = 0; i < 2; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, y[i], SCREEN_WIDTH, 0.5)];
        view.backgroundColor = [UIColor grayColor];
        [self.sv addSubview:view];
    }
    
    self.registerTFArray = @[@"e-mail",@"用户名",@"密码"];
    CGFloat fieldH = 40.0f;
    for (int i = 0; i < self.registerTFArray.count; i++) {
        UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH + 15, 10 + i * fieldH, SCREEN_WIDTH - 30, fieldH)];
        field.tag = 402 + i;
        field.delegate = self;
        field.placeholder = self.registerTFArray[i];
        field.borderStyle = UITextBorderStyleNone;
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        if (i == 1) {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10 + SCREEN_WIDTH, 50, SCREEN_WIDTH - 10, 0.5)];
            lineView.backgroundColor = [UIColor grayColor];
            [self.sv addSubview:lineView];
        } else if (i == 2){
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10 + SCREEN_WIDTH, 91, SCREEN_WIDTH - 10, 0.5)];
            lineView.backgroundColor = [UIColor grayColor];
            [self.sv addSubview:lineView];
            field.secureTextEntry = YES;
        }
        [self.sv addSubview:field];
    }
    
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registerBtn.frame = CGRectMake(10 + SCREEN_WIDTH, 10 + self.registerTFArray.count * fieldH + 10, SCREEN_WIDTH - 20, fieldH);
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    UIImage *image = [UIImage imageNamed:@"cancle_button_click"];
    UIImage *newImage = [image stretchableImageWithLeftCapWidth:5 topCapHeight:20];
    [registerBtn setBackgroundImage:newImage forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.sv addSubview:registerBtn];
}

#pragma mark - textField协议方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - scrollView协议方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.tag == 33) {
        [self.sv endEditing:YES];
    } else if (scrollView.tag == 500){
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.tag == 33) {
        CGPoint point = scrollView.contentOffset;
        if (point.x / SCREEN_WIDTH) {
            //注册页面
            [UIView animateWithDuration:0.5 animations:^{
                self.bottomView.frame = CGRectMake(80, 20, 40, 5);
            }];
        } else {
            //登陆页面
            [UIView animateWithDuration:0.5 animations:^{
                self.bottomView.frame = CGRectMake(0, 20, 40, 5);
            }];
        }
    }
}

#pragma mark - tableView协议方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 3;
    } else if (section == 2) {
        return 2;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *cellIdentifier = @"myselfFirstCell";
        MyselfFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyselfFirstCell" owner:self options:nil] lastObject];
        }
        return cell;
    } else {
        static NSString *cellIdentifier = @"myselfCell";
        MyselfCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyselfCell" owner:self options:nil] lastObject] ;
        }
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 100.0f;
    }
    return 40.0f;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1 && indexPath.row == 1) {
        // 附近人的交易
        NearbyTradeVC *nearbyVC = [[NearbyTradeVC alloc] init];
        nearbyVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:nearbyVC animated:YES];
    } else if (indexPath.section == 0 && indexPath.row == 0) {
        // 个人信息
        PersonInfoViewController *personInfoVC = [[PersonInfoViewController alloc] init];
        personInfoVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:personInfoVC animated:YES];
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        //已买到的宝贝
        
    }
}

#pragma mark - 按钮点击
-(void)landBtnClick{
    //如果账号登陆成功
    self.navigationItem.titleView = nil;
    self.navigationItem.title = @"我";
    isLandIn = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self.sv.hidden = YES;
    }];
    [self.sv endEditing:YES];
    
    NSString *nameStr = [(UITextField *)[self.sv viewWithTag:400] text];
    NSString *pwdStr = [(UITextField *)[self.sv viewWithTag:401] text];
    NSLog(@"nameStr = %@,pwdStr = %@",nameStr,pwdStr);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *dic = @{
                          @"username":nameStr,
                          @"userpwd":pwdStr
                          };
#warning 登陆数据请求
    [manager GET:LOGIN_URL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        
//        if ([json isKindOfClass:[NSDictionary class]]) {
//            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:json];
//            NSLog(@"打印字典%@",dic);
//        } else if ([json isKindOfClass:[NSArray class]]) {
//            NSArray *array = [NSArray arrayWithArray:json];
//            NSLog(@"打印数组%@",array);
//        }
        NSString *str = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"land error = %@",error);
    }];
    
    
}

//@[@"e-mail",@"用户名",@"密码"];
-(void)registerBtnClick{
    NSArray *array = @[@"email",@"username",@"userpwd"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (int i = 0; i < self.registerTFArray.count; i++) {
        UITextField *tf = (UITextField *)[self.sv viewWithTag:(402+i)];
        [dic setObject:tf.text forKey:array[i]];
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:REGISTER_URL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"消息" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [av show];
        if ([str isEqualToString:@"注册成功"]) {
            self.isRegisterSuccess = YES;
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"register error = %@",error);
    }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (self.isRegisterSuccess) {
        [UIView animateWithDuration:0.5 animations:^{
            self.sv.contentOffset = CGPointZero;
            self.bottomView.frame = CGRectMake(0, 20, 40, 5);
        }];
    }
}

//忘记密码
-(void)forgetBtnClick{
    ForgetVC *vc = [[ForgetVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

//导航栏按钮
-(void)naviBtnClick:(UIButton *)btn{
    if ((btn.tag - 500) == 0) {
        [UIView animateWithDuration:0.5 animations:^{
            self.bottomView.frame = CGRectMake(0, 20, 40, 5);
            self.sv.contentOffset = CGPointMake(0, 0);
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            self.bottomView.frame = CGRectMake(80, 20, 40, 5);
            self.sv.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
